#include <iostream>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>

typedef websocketpp::server<websocketpp::config::asio> websocket_server;



//http回调函数
void http_callback(websocket_server* server,websocketpp::connection_hdl hdl)
{
  
   websocket_server::connection_ptr conn=server->get_con_from_hdl(hdl);
   std::cout<<conn->get_request_body()<<std::endl;

   websocketpp::http::parser::request req=conn->get_request();


   std::cout<<"method: "<<req.get_method()<<std::endl;
   std::cout<<"uri: "<<req.get_uri()<<std::endl;

}


//消息回调函数
void msmsg_callback(websocket_server* server,websocketpp::connection_hdl hdl,websocket_server::message_ptr msg)
{
   websocket_server::connection_ptr conn=server->get_con_from_hdl(hdl);

   std::cout<<"wsmsg: "<<msg->get_payload()<<std::endl;
   std::string rsp="client say: "+msg->get_payload();

   conn->send(rsp,websocketpp::frame::opcode::text);
}

//http回调函数
void OnHttp(websocket_server *server, websocketpp::connection_hdl hdl)
{
    std::cout << "处理http请求" << std::endl;
    websocket_server::connection_ptr con = server->get_con_from_hdl(hdl);

    con->append_header("Content-Type", "text/html; charset=utf-8");

    std::stringstream ss;
    ss << "<!DOCTYPE html><head>"
       << "<meta charset="
          "UTF - 8"
          ">"
       << "<meta name="
          "viewport "
          " content="
          " width = device - width,initial - scale = 1.0 "
          ">"
       << "<title>Document</title>"
       << "</head>"
       << "<body>"
       << "你好，这是小王的测试网页"
       << "</body>"
       << "</html>";

    con->set_body(ss.str());
    con->set_status(websocketpp::http::status_code::ok);
}

int main()
{

    // 使用websocketpp创建服务器
    websocketpp::server<websocketpp::config::asio> server;

    // 设置打印日志
    server.set_access_channels(websocketpp::log::alevel::none);

    // 初始化asio
    server.init_asio();

    // 注册http请求函数

    server.set_http_handler(std::bind(&http_callback, &server, std::placeholders::_1));

    server.set_message_handler(std::bind(&msmsg_callback,&server,std::placeholders::_1,std::placeholders::_2));


    // 启用地址复用
    server.set_reuse_addr(true);

    // 监听
    server.listen(15535);

    // 接受连接

    server.start_accept();

    // 启动服务
    server.run();

    return 0;
}

